<?php


namespace App\Models;


use App\Exceptions\ApiException;
use App\Services\Base\CacheService;
use App\Traits\BaseTrait;
use Illuminate\Database\Eloquent\Model;

class BaseModel extends Model
{
    use BaseTrait;

    public static $lib_status = [
        STATUS_DISABLED => '禁用',
        STATUS_ENABLED => '启用',
    ];

    public function getConnSuffix($uid = 0)
    {
        return "mysql";
    }

    public function getTableSuffix($uid = 0)
    {
        return $this->table;
    }

    /**
     * @param int $uid
     * @return BaseModel
     */
    public function getModel($uid = 0)
    {
        return $this->setConnection($this->getConnSuffix($uid))->setTable($this->getTableSuffix($uid));
    }


    public static function getOne($id, $throw = true)
    {
        $model = self::query()->find($id);
        if (!$model && $throw) {
            throw new ApiException("数据不存在");
        }
        return $model;
    }

    public static function list($attribute = "*", $where = [], $params = [])
    {
        $per_page = $params['per_page'] ?? 20;
        $page = $params['page'] ?? 1;
        $order_desc = $params['order.desc'] ?? null;

        $query = self::query()->where($where)->select($attribute);
        $order_desc && $query->orderByDesc($order_desc);
        $paginator = $query->paginate($per_page, '*', 'page', $page);
        return [
            'list' => $paginator->items(),
            'per_page' => $paginator->perPage(),
            'page' => $paginator->currentPage(),
            'last_page' => $paginator->lastPage(),
            'total' => $paginator->total()
        ];
    }


    public static function getAll($enable = false)
    {
        $key = static::CACHE_NAME . ($enable ? ":enable" : ":all");
        $data = CacheService::get($key);
        if (!$data) {
            if ($enable) {
                $data = self::query()
                    ->where('status', STATUS_ENABLED)
                    ->get()->toArray();
            } else {
                $data = self::query()
                    ->get()->toArray();
            }
            CacheService::set(static::CACHE_NAME, $data);
        }
        return $data;
    }


}
